package com.jubotech.business.web.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.protobuf.util.JsonFormat;
import com.jubotech.business.web.dao.TaskTimeDao;
import com.jubotech.business.web.dao.TimeTaskDetailsDao;
import com.jubotech.business.web.dao.WxAccountDao;
import com.jubotech.business.web.dao.WxContactDao;
import com.jubotech.business.web.domain.TaskTimeInfo;
import com.jubotech.business.web.domain.TimeTaskDetails;
import com.jubotech.business.web.domain.WxAccountInfo;
import com.jubotech.business.web.domain.WxContactInfo;
import com.jubotech.business.web.query.TaskTimeQuery;
import com.jubotech.framework.common.ResultInfo;
import com.jubotech.framework.netty.utils.MsgIdBuilder;
import com.jubotech.framework.util.DateUtil;

import Jubo.JuLiao.IM.Wx.Proto.AddFriendsTask.AddFriendsTaskMessage;
import Jubo.JuLiao.IM.Wx.Proto.PostSNSNewsTask.PostSNSNewsTaskMessage;
import Jubo.JuLiao.IM.Wx.Proto.PostSNSNewsTask.PostSNSNewsTaskMessage.AttachmentMessage;
import Jubo.JuLiao.IM.Wx.Proto.PostSNSNewsTask.PostSNSNewsTaskMessage.VisibleMessage;
import Jubo.JuLiao.IM.Wx.Proto.PostSNSNewsTask.PostSNSNewsTaskMessage.VisibleMessage.EnumVisibleType;
import Jubo.JuLiao.IM.Wx.Proto.WeChatGroupSendTask.WeChatGroupSendTaskMessage;
import tk.mybatis.mapper.entity.Example;

@Service
@Transactional // 支持事务
public class TaskTimeService {
	  
	@Autowired
	private TaskTimeDao taskTimeDao;
	
	@Autowired
	private TimeTaskDetailsDao  timeTaskDetailsDao;
	
	@Autowired
	private WxAccountDao weChatAccountDao;
  
	@Autowired
	private WxContactDao weChatContactDao;
 
	public PageInfo<TaskTimeInfo> pageList(TaskTimeQuery query) {
		PageHelper.startPage(query.getPage(), query.getRows());
         
		Example example = new Example(TaskTimeInfo.class);
		Example.Criteria criteria = example.createCriteria();
		 
		criteria.andEqualTo("cid", query.getCid());
		if (null != query.getTasktype()) {
			criteria.andEqualTo("tasktype", query.getTasktype());
		}
		if (null != query.getState()) {
			criteria.andEqualTo("state", query.getState());
		}
		example.orderBy("id").desc();
		return new PageInfo<>(taskTimeDao.selectByExample(example));
		 
	}
	

	public TaskTimeInfo findTaskTimeInfoByid(Integer id) {
		return taskTimeDao.findTaskTimeInfoByid(id);
	}
 

	public ResultInfo delete(Integer id) {
		ResultInfo res = new ResultInfo();
		try {
			//先删除子任务
			timeTaskDetailsDao.deleteByTid(id);
			//再删除主任务
			TaskTimeInfo user = new TaskTimeInfo();
			user.setId(id);
			taskTimeDao.delete(user);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultInfo.fail("添加失败");
		}
		return res;
	}

	public void updateState(TaskTimeInfo info) {
		taskTimeDao.updateState(info);
	}
	
	public List<TaskTimeInfo> findTaskTimeByTime(String execute_time){
		return taskTimeDao.findTaskTimeByTime(execute_time);
	}
	
	public List<TimeTaskDetails> findTimeTaskDetailsByTid(Integer tid){
		return timeTaskDetailsDao.findTimeTaskDetailsByTid(tid);
	}
	 
	
	private static void saveCircleSendTimeTaskDetail(TaskTimeInfo info,List<String> friendWechatList,String wechatId ,TimeTaskDetailsDao  timeTaskDetailsDao){
		if(null != info.getId()){
			List<String> newfriendWechatList =  null;
			if( null != friendWechatList && friendWechatList.size()>0){
				//friendWechatList去除重复
				newfriendWechatList = removeRepeat(friendWechatList);
			}
	    	
	    	TimeTaskDetails detail = new TimeTaskDetails();
	    	detail.setTid(info.getId());
	    	detail.setExecute_time(info.getExecute_time());
	    	timeTaskDetailsDao.insert(detail);
	    	
	    	if(null != detail.getId()){
	    		//设置附件
	    		AttachmentMessage.Builder attachment = AttachmentMessage.newBuilder();
	    		attachment.setTypeValue(info.getRestype());
	    		attachment.addAllContent(stringToList(info.getAttachtcontent()));
	    		//设置可见范围
	    		VisibleMessage.Builder  visible  = VisibleMessage.newBuilder();
	    		visible.setTypeValue(EnumVisibleType.WhoInvisible_VALUE);//不给谁看
	    		visible.setFriends(ListToString(newfriendWechatList));
	    		 
	    		//按微信号生成需要发的消息内容
	    		PostSNSNewsTaskMessage.Builder buider = PostSNSNewsTaskMessage.newBuilder();
				buider.setContent(info.getContent());
				buider.setAttachment(attachment);
				buider.setTaskId(detail.getId());
				buider.setWeChatId(wechatId);
				buider.setComment(info.getComment());
				buider.setVisible(visible);
				PostSNSNewsTaskMessage msg = buider.build();
				String json = null;
				if (null != msg) {
					try {
						json = JsonFormat.printer().print(msg);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if(!StringUtils.isEmpty(json)){
					TimeTaskDetails tds =  new TimeTaskDetails();
					tds.setId(detail.getId());
					tds.setJson_content(json);
					timeTaskDetailsDao.updateJsonContent(tds);
				}
	    	}
	    }
		
	}
	
	private static void saveGroupSendTimeTaskDetail(TaskTimeInfo info,List<String> friendWechatList,String wechatId ,TimeTaskDetailsDao  timeTaskDetailsDao){
		if(null != info.getId() ){
			List<String> newfriendWechatList = null;
			if(null != friendWechatList && friendWechatList.size()>0){
				newfriendWechatList = removeRepeat(friendWechatList);//friendWechatList去除重复
			}
	    	 
	    	TimeTaskDetails detail = new TimeTaskDetails();
	    	detail.setTid(info.getId());
	    	detail.setExecute_time(info.getExecute_time());
	    	timeTaskDetailsDao.insert(detail);
	    	
	    	if(null != detail.getId()){
	    		//按微信号生成需要群发的消息内容
				WeChatGroupSendTaskMessage.Builder buider = WeChatGroupSendTaskMessage.newBuilder();
				buider.setContent(info.getContent());
				buider.setContentTypeValue(info.getRestype());
				buider.setTaskId(detail.getId());
				buider.setWeChatId(wechatId);
				buider.addAllFriendIds(newfriendWechatList);
				WeChatGroupSendTaskMessage msg = buider.build();
				String json = null;
				if (null != msg) {
					try {
						json = JsonFormat.printer().print(msg);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if(!StringUtils.isEmpty(json)){
					TimeTaskDetails tds =  new TimeTaskDetails();
					tds.setId(detail.getId());
					tds.setJson_content(json);
					timeTaskDetailsDao.updateJsonContent(tds);
				}
	    	}
	    }
		
	}
	
	
	private static void saveAddFriendsTaskDetail(TaskTimeInfo info ,TimeTaskDetailsDao  timeTaskDetailsDao){
		if(null != info.getId()){
			if(!org.apache.commons.lang3.StringUtils.isEmpty(info.getContent()) ) {
				List<String>	friendAddList = stringToList(info.getContent());
				
				Date newDate = DateUtil.convertString2Date(info.getExecute_time(), DateUtil.DATE_FORMAT_4);
				Integer betweenTime = 30;
				  
				if(null != friendAddList && friendAddList.size()>0){
					for(String phone:friendAddList){
						 AddFriendsTaskMessage.Builder bd = AddFriendsTaskMessage.newBuilder();
						 bd.setWeChatId(info.getWechatids());
						 bd.addPhones(phone);
						 bd.setTaskId(MsgIdBuilder.getId());
						 AddFriendsTaskMessage msg = bd.build();
								  
						if (null != msg) {
							try {
								String json  = JsonFormat.printer().print(msg);
								if(!StringUtils.isEmpty(json)){
									TimeTaskDetails detail = new TimeTaskDetails();
							    	detail.setTid(info.getId());
							    	detail.setExecute_time(DateUtil.convertDate2String(newDate, DateUtil.DATE_FORMAT_2));
							    	detail.setJson_content(json);
							    	timeTaskDetailsDao.insert(detail);
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
					newDate = DateUtil.offsetSecode(newDate, betweenTime);
					
					System.out.println(DateUtil.convertDate2String(newDate, DateUtil.DATE_FORMAT_2));
				 
			   }
	    	
			}
	    }
		
	}
	
  
    private static List<String> stringToList(String str){
    	List<String> list = new ArrayList<>();
    	if(!StringUtils.isEmpty(str)){
    		String [] s = str.split(",");
    		if(null != s && s.length>0){
    			for(int i=0;i<s.length;i++){
    				list.add(s[i]);
    			}
    		}else{
    			list.add(str);
    		}
    	}
    	return list;
    }
    
    private static String ListToString(List<String> list){
    	String s = "";
    	if(null != list && list.size()>0){
    		for(int i=0;i<list.size();i++){
    			s = s + list.get(i) +",";
    		}
    	}
    	if(!StringUtils.isEmpty(s) && s.endsWith(",")){
    		s = s.substring(0, s.length()-1);
    	}
    	return s;
    	
    }
    
    private static List<String> removeRepeat(List<String> list){
    	Set<String> set = new  HashSet<>(); 
        List<String> newList = new  ArrayList<String>(); 
        for (String cd:list) {
           if(set.add(cd)){
               newList.add(cd);
           }
       }
    	return newList;
    }
    
    /**
     * 添加定时任务
     * @param info
     * @return
     */
    public ResultInfo saveTask(TaskTimeInfo info) {
    	ResultInfo res = new ResultInfo();
		try {
			 
			//主任务存储数据库
			info.setState(1);//1开启中 0已完成
		    taskTimeDao.insert(info);
		     
		    if(info.getTasktype()==3) {//自动加好友
				saveAddFriendsTaskDetail(info, timeTaskDetailsDao);
			}else {
			    List<WxAccountInfo> weList  =	weChatAccountDao.findWeChatAccountInfoByCid(info.getCid());
				if(null != weList && weList.size()>0) {
					for (int i = 0; i < weList.size(); i++) {
						String wechatId =  weList.get(i).getWechatid();
						//子任务分别处理  存储子任务详情 
						if(info.getTasktype()==1){//添加群发任务
						   Map<String, List<String>> maps = new HashMap<String,List<String>>();
						   List<WxContactInfo>  contactList = weChatContactDao.findContactinfoByWeChatId(info.getCid(), wechatId);
						   if(null != contactList && contactList.size()>0) {
							   List<String> wechatList = new ArrayList<String>();
							   Integer contactSize = contactList.size();
							   Integer index = 1; 
							   for(int j=0;j<contactSize;j++) {
								   if(j == index * 99) {
									   maps.put(wechatId+j, wechatList);
									   wechatList= new ArrayList<String>();
									   index  = index +1;
								   }
								   
								   WxContactInfo wechatContact = contactList.get(j);
								   wechatList.add(wechatContact.getFriendid());
								   
								   if(j==contactSize-1 && j!=index * 99) {
									   maps.put(wechatId+j, wechatList);
								   }
							   }
						   }
						   
						   System.out.println("mapsize:"+maps.size());
						   for(String key : maps.keySet()) {
							   List<String> wechatList= maps.get(key);
							   saveGroupSendTimeTaskDetail(info, wechatList, wechatId, timeTaskDetailsDao);
					       }
						   
						}else if(info.getTasktype()==2){//发朋友圈
						   saveCircleSendTimeTaskDetail(info, stringToList(info.getWhoinvisible()), wechatId, timeTaskDetailsDao);
						}
					}
				}
			}
		} catch (Exception e) {
			e.fillInStackTrace();
			return ResultInfo.fail("添加失败");
		}

		return res;
	}
    

}
